import { useState, useEffect, useRef, useMemo } from 'react';
import { Button, Space } from 'antd';
import { Table, MF, Form } from 'com';
import menuStore from 'store/menu';
import { AddStudents, UpdateStudents, ChangeStatus, Search, ChangeRecord } from 'api/students';
import { getStudentStatus, getStudentRecords } from 'api/dictionary';
import { NavLink } from 'react-router-dom';
import dayjs from 'dayjs';

export default () => {
    /**
     * 列表
     */
    const [list, setList] = useState([]);
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 学生信息
     */
    const [student, setStudent] = useState({});
    /**
     * 总条数
     */
    const [total, setTotal] = useState(0);
    /**
     * 状态列表
     */
    const [statusList, setStatusList] = useState([{ label: '所有', value: 0 }]);
    /**
     * 学生记录
     */
    const [records, setRecords] = useState([]);
    /**
     * 搜索模型
     */
    const [searchModel, setSearchModel] = useState({
        pageNo: 1,
        pageSize: 10,
        status: 0,
    });
    /**
     * 添加MF引用
     */
    const addMF = useRef();
    /**
     * 修改状态MF引用
     */
    const changeMF = useRef();
    /**
     * 档案MF引用
     */
    const recordMF = useRef();
    /**
     * 列
     */
    const cols = [
        {
            title: '学生姓名',
            dataIndex: 'name',
            align: 'center'
        },
        {
            title: '身份证号',
            dataIndex: 'idNo',
            align: 'center'
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            align: 'center'
        },
        {
            title: '头像',
            dataIndex: 'avatar',
            align: 'center',
            render: text => <img src={process.env.REACT_APP_BASE_URL + text} width={100} height={100} />
        },
        {
            title: '班级',
            dataIndex: 'class_name',
            align: 'center'
        },
        {
            title: '状态',
            dataIndex: 'status_name',
            align: 'center',
        },
        {
            title: '入学日期',
            dataIndex: 'join_date',
            align: 'center',
            render: text => dayjs(text).format('YYYY-MM-DD')
        },
        {
            title: '地址',
            dataIndex: 'address',
        },
        {
            title: '操作',
            align: 'center',
            width: 130,
            render: (text, row) => <Space>
                {
                    menuStore.auth('updateStudents') && <Button type="link" size="small" onClick={() => {
                        setStudent({ ...row, join_date: dayjs(row.join_date), class_id: { id: row.class_id, name: row.class_name } });
                        addMF.current.show();
                    }}>修改</Button>
                }
                {
                    menuStore.auth('ChangeStudentStatus') && <Button type="link" size="small" onClick={() => {
                        setStudent({ ...row });
                        changeMF.current.show();
                    }}>更改状态</Button>
                }
                {
                    menuStore.auth('record') && row.status !== 25 && <Button type="link" size="small" onClick={() => {
                        setStudent({ ...row });
                        recordMF.current.show();
                    }}>更改档案</Button>
                }
                {
                    menuStore.auth('studentEmergencyList', 'addStudentEmergency') && <NavLink style={{ whiteSpace: 'nowrap' }} to={"/studentEmergency/" + row.id}>紧急联系人管理</NavLink>
                }
            </Space>
        }
    ]
    /**
     * 搜索表单配置项
     */
    const searchOptions = useMemo(() => ({
        ...(menuStore.auth('students') ? {
            status: {
                title: '状态',
                tag: 'select',
                style: { width: 80 },
                values: statusList
            },
            name: {
                title: '学生姓名',
                max: 20,
            },
            idNo: {
                title: '身份证号',
                max: 18
            },
            phone: {
                title: '手机号',
                max: 11
            },
            class_id: {
                title: '班级',
                tag: 'cs',
                clear: true
            },
            button: {
                text: '搜索',
                tag: 'button',
                type: 'primary',
                htmlType: 'submit',
                loading
            },
        } : {})
        ,
        ...(menuStore.auth('addStudents') ? {
            add: {
                text: '添加学生',
                tag: 'button',
                type: 'primary',
                click: () => {
                    setStudent({ record: 20 });
                    addMF.current.show();
                }
            }
        } : {})
    }), [loading, statusList]);
    /**
     * 添加修改表单配置项
     */
    const options = useMemo(() => ({
        name: {
            title: '学生姓名',
            required: true,
            max: 20
        },
        idNo: {
            title: '身份证号',
            required: true,
            max: 18,
            rules: [{ pattern: /^\d{17}[\dXx]$/, message: '身份证号不正确' }]
        },
        phone: {
            title: '手机号',
            max: 11,
            rules: [{ patter: /^1[3-9]\d{9}$/, message: '手机号不正确' }]
        },
        avatar: {
            title: '头像',
            tag: 'upload',
            tip: '请勿上传超过2m的图片文件',
            rules: [{
                validator(rule, value) {
                    if (value instanceof File) {
                        const { size, type } = value;
                        if (!/^image\/.+$/.test(type)) {
                            return Promise.reject('请上传图片文件');
                        }
                        if (size > 1024 * 1024 * 2) {
                            return Promise.reject('请勿上传超过2m的文件');
                        }
                    }
                    return Promise.resolve();
                }
            }]
        },
        ...(student.id ? {} : {
            class_id: {
                title: '班级',
                tag: 'cs',
                required: true
            }
        }),
        ...(student.id ? {} : {
            record: {
                title: '档案',
                tag: 'select',
                required: true,
                values: records.filter(c => c.value === 20 || c.value === 21),
                attrs: {
                    onChange(value) {
                        setStudent(v => ({ ...v, record: value }))
                    }
                }
            }
        }),
        ...(student.record === 21 ? {
            oldSchool: {
                title: '原学校',
                max: 20,
                required: true
            }
        } : {}),
        join_date: {
            title: '入学日期',
            tag: 'date',
            required: true
        },
        address: {
            title: '地址',
            max: 100,
            min: 6,
            required: true
        }
    }), [student]);
    /**
     * 修改状态表单配置项
     */
    const changeOptions = useMemo(() => {
        const [a, ...rest] = statusList;
        return {
            status: {
                title: '状态',
                tag: 'select',
                required: true,
                values: rest.filter(c => c.value === 23 || c.value === 24),
                rules: [{
                    validator(rule, value) {
                        if (value === student.status) {
                            return Promise.reject('状态一致，无需修改');
                        }
                        return Promise.resolve();
                    }
                }]
            }
        }
    }, [statusList, student]);
    /**
     * 档案表单配置项
     */
    const recordOptions = useMemo(() => {
        let ids = [];
        switch (student.status) {
            //如果是正常或休学
            case 23:
            case 24:
                ids = [22, 27, 28]; //那么可以转出、调班、毕业
                break;
            case 26:
                ids = [21];
                break;
        }

        return {
            record: {
                title: '档案',
                tag: 'select',
                required: true,
                values: records.filter(c => ids.includes(c.value)),
                attrs: {
                    onChange(value) {
                        setStudent(v => ({ ...v, record: value }));
                    }
                }
            },
            date: {
                title: '日期',
                required: true,
                tag: 'date'
            },
            ...(student.record === 22 ? {
                class_id: {
                    title: '新班级',
                    tag: 'cs',
                    required: true
                }
            } : student.record === 27 ? {
                school: {
                    title: '新学校',
                    required: true,
                    max: 20
                }
            } : student.record === 21 ? {
                oldSchool: {
                    title: '原学校',
                    required: true,
                    max: 20
                },
                class_id: {
                    title: '转入班级',
                    required: true,
                    tag: 'cs'
                }
            } : null)
        }
    }, [student]);

    menuStore.auth('students', 'addStudents') && useEffect(() => {
        (async () => {
            try {
                const statusList = await getStudentStatus();
                setStatusList(v => [...v, ...statusList.map(c => ({ label: c.name, value: c.id }))]);
            } catch (error) { }
            try {
                const records = await getStudentRecords();
                setRecords(records.map(c => ({ label: c.name, value: c.id })));
            } catch (error) { }
        })()
    }, []);

    menuStore.auth('students') && useEffect(() => {
        (async () => {
            try {
                setLoading(true);
                const { data, total } = await Search({ ...searchModel });
                setList(data);
                setTotal(total);
            } catch (error) { }
            setLoading(false);
        })()
    }, [searchModel]);

    /**
     * 提交
     * @param {*} values 
     */
    const confirm = async values => {
        addMF.current.start();
        try {
            await (student.id ? UpdateStudents : AddStudents)({ ...values, id: student.id, join_date: dayjs(values.join_date).format('YYYY-MM-DD') });
            setSearchModel(v => ({ ...v }));
            addMF.current.hide();
        } catch (error) {
            console.log(error);
        }
        addMF.current.stop();
    }

    /**
     * 更改状态
     * @param {*} values 
     */
    const change = async values => {
        changeMF.current.start();
        try {
            await ChangeStatus({ id: student.id, ...values });
            setSearchModel(v => ({ ...v }));
            changeMF.current.hide();
        } catch (error) {
            console.log(error);
        }
        changeMF.current.stop();
    }

    /**
     * 更改学生档案
     * @param {*} values 
     */
    const changeRecord = async values => {
        recordMF.current.start();
        try {
            await ChangeRecord({ id: student.id, ...values, date: dayjs(values.date).format('YYYY-MM-DD') });
            setSearchModel(v => ({ ...v }));
            recordMF.current.hide();
        } catch (error) {
            console.log(error);
        }
        recordMF.current.stop();
    }

    return <div>
        <h3>学生列表</h3>
        <hr />
        {menuStore.auth('students', 'addStudents') && <Form options={searchOptions} values={searchModel} onFinish={v => setSearchModel({ ...searchModel, ...v, pageNo: 1 })} attrs={{ layout: 'inline' }} />}
        <p></p>
        {menuStore.auth('students') && <Table cols={cols} data={list} loading={loading} page={searchModel} total={total} onChange={setSearchModel} />}
        {menuStore.auth('addStudents', 'updateStudents') && <MF onFinish={confirm} ref={addMF} options={options} title={student.id ? '修改学生' : '添加学生'} lw={80} values={student} />}
        {menuStore.auth('ChangeStudentStatus') && <MF onFinish={change} ref={changeMF} options={changeOptions} title="修改状态" lw={50} values={student} />}
        {menuStore.auth('record') && <MF onFinish={changeRecord} ref={recordMF} options={recordOptions} title="更改档案" lw={75} values={student} />}
    </div>
}